package com.snopy.concurrency.base;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author snopy
 * @version 1.0.0
 * @classname AddSubDemo
 * @description
 * @email 77912204@qq.com
 * @date 2022/06/23 8:34
 */
@Slf4j
public class AddSubDemo {

    int num = 0;
    Lock lock = new ReentrantLock();
    public static void main(String[] args) throws InterruptedException {

        AddSubDemo asd = new AddSubDemo();
        asd.test();
        //asd.test1();

    }
    public void test() throws InterruptedException {
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 10000; i++) {
                //synchronized (this){
                    lock.lock();
                    num++;
                    lock.unlock();
                //}

            }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 10000; i++) {
                //synchronized (this) {
                lock.lock();
                    num--;
                lock.unlock();
                //}
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.info("num:{}",num);

    }
    public void test1(){
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 10000; i++) {
                num--;
            }
        });
        t1.start();
    }
}
